//
//  NSObject+Observer.m
//  OberverTest
//
//  Created by ma c on 2017/8/17.
//  Copyright © 2017年luojianzhen. All rights reserved.
//

#import "NSObject+Observer.h"
#import <objc/runtime.h>

static const char associateLengthKey;

@implementation NSObject (Observer)

- (void)addMonitor:(NSObject *)object key:(NSString *)key option:(NSKeyValueObservingOptions)option callback:(OberverCallback)callback{
    if (callback) {
        objc_setAssociatedObject(self, &associateLengthKey, callback, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    [object addObserver:self forKeyPath:key options:option context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    OberverCallback callback = objc_getAssociatedObject(self, &associateLengthKey);
    if (callback) {
        callback(keyPath,object,change);
    }
}


@end
